import cgi
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
import re

class CourseInfo(db.Model):
	id=db.StringProperty()
	email=db.StringProperty()

class LogSenderHandler(InboundMailHandler):
	def receive(self, message):
		matches=re.findall("[A-Z]{2}[0-9]{3}",message.subject.upper())+re.findall("\s?([^\s]*)\s*CLUB",message.subject.upper())
		
		toaddr=[]
		for course in matches:
			recepients=db.GqlQuery("SELECT * FROM CourseInfo WHERE id = '%s'"%course)
			toaddr+=[i.email for i in recepients]
		if len(toaddr)==0:
			return
		message.reply_to=message.sender
		message.sender="postman@iiserk-mailbox.appspotmail.com"
		message.to=toaddr
		logging.info("Delivering mail from %s"%message.reply_to)
		message.send()

application = webapp.WSGIApplication([LogSenderHandler.mapping()])


def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()

